package com.guslegend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.guslegend.enums.AddressEnum;
import com.guslegend.interceptor.LoginInterceptor;
import com.guslegend.mapper.AddressMapper;
import com.guslegend.model.AddressDO;
import com.guslegend.model.LoginUser;
import com.guslegend.request.AddressAddRequest;
import com.guslegend.service.AddressService;
import com.guslegend.vo.AddressVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: guslegend
 * @description: 公司收发货地址表
 * @create: 2025-05-24 08:42
 **/
@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public AddressVO detail(long id) {
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>().eq("id", id));
        AddressVO addressVO=new AddressVO();
        BeanUtils.copyProperties(addressDO,addressVO);
        return addressVO;
    }

    @Override
    public int saveAddress(AddressAddRequest addressAddRequest) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        AddressDO addressDO = new AddressDO();
        addressDO.setUserId(loginUser.getId());
        BeanUtils.copyProperties(addressAddRequest, addressDO);

        // 设置当前时间为创建时间
       // 数据库 自动插入当前时间

        log.info("addressAddRequest: {}", addressAddRequest);
        log.info("addressDO: {}", addressDO);

        // 查找是否设为默认地址，如果设置默认地址，去数据库查找以前的默认地址并修改
        if (addressDO.getDefaultStatus() != null && addressDO.getDefaultStatus() == 1) {
            AddressDO defaultAddress = addressMapper.selectOne(
                    new QueryWrapper<AddressDO>()
                            .eq("user_id", addressDO.getUserId())
                            .eq("default_status", AddressEnum.DEFAULT_ADDRESS.getStatus())
            );

            // 修正逻辑：仅当找到旧的默认地址时才更新
            if (defaultAddress != null) {
                defaultAddress.setDefaultStatus(AddressEnum.COMMON_ADDRESS.getStatus());
                int updateRows = addressMapper.update(
                        defaultAddress,
                        new QueryWrapper<AddressDO>().eq("id", defaultAddress.getId()) // 使用id而非userId
                );
                log.info("默认地址更新结果：{}", updateRows);
            }
        }

        int rows = addressMapper.insert(addressDO);
        log.info("新增收货地址成功，影响行数：{}", rows);
        return rows;
    }

    @Override
    public int delete(long addressId) {
        int rows=addressMapper.deleteById(addressId);
        return rows;
    }

    @Override
    public Object getAddressList() {
        LoginUser loginUser=LoginInterceptor.threadLocal.get();
        List<AddressDO>addressDOList=addressMapper.selectList(new QueryWrapper<AddressDO>().eq("user_id",loginUser.getId()));
        //jdk8 lambda表达式 DO转换VO
        List<AddressVO> addressVOList = addressDOList.stream().map(AddressDO -> {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(AddressDO, addressVO);
            return addressVO;
        }).collect(Collectors.toList());
        log.info("{}的全部收货地址: {}", loginUser.getName(), addressVOList);
        return addressVOList;
    }
}